package com.hxd.otc.base;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.baidu.mobstat.StatService;
import com.hxd.otc.utils.StatusBarHelper;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

/**
 * Created by lzy on 2018/11/21 0021.
 * description ${dialogFragment 基本类}
 */
public abstract class BaseDialogFragment extends DialogFragment {

    protected View mRootView;
    private Unbinder mUnBinder;

    private boolean isPrepared;
    private boolean isFirst = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBundle(getArguments());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final Window window = getDialog().getWindow();
        if (mRootView != null) {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) parent.removeView(mRootView);
        } else {
            mRootView = inflater.inflate(getLayoutId(), container, false);
        }
        assert window != null;
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//注意此处
        onDialogAnim(window);
        if (Build.VERSION.SDK_INT >= 21) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            StatusBarHelper.setStatusBarLightMode(window);
        }
        return mRootView;
    }

    protected void onDialogAnim(Window window) {
    }


    protected abstract int getLayoutId();

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getDialog().getWindow().setLayout(MATCH_PARENT, MATCH_PARENT);
        mUnBinder = ButterKnife.bind(this, mRootView);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        lazyLoad();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    protected void lazyLoad() {
        if (!isPrepared || !getUserVisibleHint() || !isFirst) {
            return;
        }
        initView();
        initEvent();
        initData();
        isFirst = false;
    }

    protected void initBundle(Bundle arguments) {
    }

    protected abstract void initView();

    protected void initEvent() {
    }

    protected abstract void initData();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mUnBinder != null) {
            mUnBinder.unbind();
            mUnBinder = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        StatService.onPageStart(getActivity(), this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPageEnd(getActivity(), this.getClass().getSimpleName());
    }

    /**
     * replace子级Fragment
     */
    public void replaceChildFragment(@IdRes int containerViewId, Fragment fragment, String tag) {
        getChildFragmentManager()
                .beginTransaction()
                .replace(containerViewId, fragment, tag)
                .commit();
    }

    /**
     * add 子级Fragment
     */
    public void addChildFragment(@IdRes int containerViewId, Fragment fragment, String tag) {
        getChildFragmentManager()
                .beginTransaction()
                .addToBackStack(tag)
                .add(containerViewId, fragment, tag)
                .commit();
    }

    /**
     * 使用反射重写showAllowingStateLoss()方法
     * 解决调用show()方法异常
     *
     * @author fengzhen
     * @version v5.2.4, 2017/7/2 17:29
     */
    public void showAllowingStateLoss(FragmentManager manager, String tag) {
        try {
            Field mDismissed = DialogFragment.class.getDeclaredField("mDismissed");
            mDismissed.setAccessible(true);
            mDismissed.set(this, false);
            Field mShownByMe = DialogFragment.class.getDeclaredField("mShownByMe");
            mShownByMe.setAccessible(true);
            mShownByMe.set(this, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }

}
